package cn.zh.stan.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.shenyuanqing.zxingsimplify.zxing.Activity.CaptureActivity;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.zh.stan.BaseUrl;
import cn.zh.stan.ITem.CITem;
import cn.zh.stan.ITem.GItem;
import cn.zh.stan.ITem.GLItem;
import cn.zh.stan.ITem.GaItem;
import cn.zh.stan.MyApplication;
import cn.zh.stan.R;
import cn.zh.stan.adapter.GPadpter;
import cn.zh.stan.adapter.GdAdapter;
import cn.zh.stan.adapter.Gpladapter;
import cn.zh.stan.util.MyListener;
import cn.zh.stan.util.PullToRefreshLayout;
import cn.zh.stan.util.PullableListView;
import cn.zh.stan.util.ToastUtil;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class GoodsActivity extends BaseActivity implements PullableListView.OnLoadListener ,View.OnLayoutChangeListener, View.OnClickListener {

    ImageView ga_back;
    PullableListView pulist;
    GdAdapter GdAdapter;
    ArrayList<GItem> gItems=new ArrayList<GItem>();
    RadioGroup gdgroup;
    RadioButton gall;
    LinearLayout gachoice;
    PopupWindow popupWindow;
    ArrayList<GLItem> galist=new ArrayList<GLItem>();
    //当前商品标签
    GLItem glItem=null;
    GPadpter gPadpter;

    private int screenHeight = 0;
    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;
    RelativeLayout pore;
     //搜索
    TextView stxt;
    Gpladapter gpladapter;

    //弹窗队列
    ArrayList<PopupWindow> popus=new ArrayList<PopupWindow>();
   //商品类别数据
    ArrayList<CITem>ciTems=new ArrayList<CITem>();
    //记录返回的商品数据
    CITem fciTem=null;
    TextView gdclass;
    EditText mintxt,maxtxt;

    //筛选
     //判断弹窗是否可以删除
    boolean isdele=true;
    int page=1;
    //参数表明类型
    String type="0";
    //加载更多数据不清楚
    boolean isclear=true;
    //暂无数据
    TextView empty;

    PullToRefreshLayout refresh_view;
    String min="",max="",flagId="",classId="";

    MyApplication mapp;
    String uid;
    String keyword="";
    ImageView wima,gsca;
    private static final int REQUEST_SCAN = 0;

    public static final int INIT = 0;
    public static final int STOP = 2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods);
        mapp= (MyApplication) getApplication();
        uid=mapp.getSp().getString("uid","");
        initv();
        }



    public void initv(){
        gdgroup= (RadioGroup) findViewById(R.id.gdgroup);
        ga_back= (ImageView) findViewById(R.id.ga_back);
        pulist= (PullableListView) findViewById(R.id.pulist);
        gall= (RadioButton) findViewById(R.id.gall);
        stxt= (TextView) findViewById(R.id.stxt);
        wima= (ImageView)findViewById(R.id.wima);
        gsca= (ImageView)findViewById(R.id.gsca);
        empty= (TextView) findViewById(R.id.empty);

        refresh_view=(PullToRefreshLayout) findViewById(R.id.refresh_view);
        gachoice= (LinearLayout) findViewById(R.id.gachoice);
        ga_back.setOnClickListener(this);
        gachoice.setOnClickListener(this);
        stxt.setOnClickListener(this);
        GdAdapter=new GdAdapter(this,gItems,uid);

        pulist.setAdapter(GdAdapter);

        gdgroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.gall:
                        type="0";
                        break;
                    case R.id.gasale:
                        type="1";
                        break;
                    case R.id.gaprice:
                        type="2";
                        break;
                   }
                getCGoods(type,"1",flagId,classId,min,max);
              }
            });
         gall.setChecked(true);

        refresh_view.setOnRefreshListener(new MyListener(){
                    @Override
                    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                        super.onRefresh(pullToRefreshLayout);
                        getCGoods(type,"1",flagId,classId,min,max);
                      }
                   });

        pulist.setOnLoadListener(this);

        pulist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent=new Intent(GoodsActivity.this,DtailGoods.class);
                 intent.putExtra("goodsid",gItems.get(i).getGoodsId());
                 startActivity(intent);
               }
             });
        wima.setOnClickListener(this);
        gsca.setOnClickListener(this);
           }

    @Override
    public void onClick(View view) {
        int id=view.getId();
        switch (id){
            case R.id.ga_back:
                finish();
                break;
            case R.id.stxt:
                //跳转搜索
                Intent intent=new Intent(GoodsActivity.this,GASearch.class);
                startActivityForResult(intent,1);
                break;
            case R.id.wima:
                stxt.setText("客户名称/编码");
                keyword="";
                page=1;
                getCGoods(type,page +"",flagId,classId,min,max);
                wima.setVisibility(View.GONE);
                break;
            case R.id.gachoice:
              popus.clear();
              showPopUp();
                break;
            case R.id.gasure:
                String str=gdclass.getText().toString();
                if (str.equals("全部")){
                    glItem=null;
                    fciTem=null;
                }
                popupWindow.dismiss();

                min = mintxt.getText().toString();

                max = maxtxt.getText().toString();

                if (null!=glItem){
                    flagId=glItem.getFlagID();
                    }else {
                    flagId="";
                }
                 if (null!=fciTem){
                    classId=fciTem.getClassID();
                  }else {
                     classId="";
                 }
                //此处加需判断
                getCGoods(type,"1",flagId,classId,min,max);
                break;
            case R.id.clean:
                gdclass.setText("全部");
                for (int j=0;j<galist.size();j++){
                    galist.get(j).setType(0);
                    }
                gPadpter.notifyDataSetChanged();
                fciTem=null;
                glItem=null;
                mintxt.getText().clear();
                maxtxt.getText().clear();
                popupWindow.dismiss();
                break;
            case R.id.gachose:
                getPo();
                getclss();
                break;
            case R.id.gsca:
                getRuntimeRight();
                break;
            case R.id.poview:
                popupWindow.dismiss();
                break;
              }
          }



    @Override
    public void onLoad(PullableListView pullableListView) {
        new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                  isclear=false;
                  page = page + 1;
                  getCGoods(type,page +"",flagId,classId,min,max);

               }
          }.sendEmptyMessageDelayed(0, 2000);
           }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data==null){
            return;
        }
        switch (requestCode){
            case 1:
                page=1;
                keyword=data.getStringExtra("setxt");
                stxt.setText(keyword);
                wima.setVisibility(View.VISIBLE);
                getCGoods(type,page +"",flagId,classId,min,max);
                break;
           }
        if(requestCode == REQUEST_SCAN && resultCode == RESULT_OK){
            keyword=data.getStringExtra("barCode");
            page=1;
            getCGoods(type,page +"",flagId,classId,min,max);
         }
       }




    /**
     * 获得运行时权限
     */
    private void getRuntimeRight() {
        if (ContextCompat.checkSelfPermission(GoodsActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(GoodsActivity.this, new String[]{Manifest.permission.CAMERA}, 1);
        } else {
            jumpScanPage();
          }
        }

    /**
     * 跳转到扫码页
     */
    private void jumpScanPage() {
        startActivityForResult(new Intent(GoodsActivity.this, CaptureActivity.class),REQUEST_SCAN);
      }
     
     
     
     
     

    //侧滑弹窗
    private void showPopUp() {
        gPadpter = new GPadpter(this,galist);
        getLabel();
        View vp = LayoutInflater.from(this).inflate(R.layout.ga_window, null, false);
        gdclass = vp.findViewById(R.id.gdclass);
        mintxt = vp.findViewById(R.id.mintxt);
        maxtxt = vp.findViewById(R.id.maxtxt);
        View poview=vp.findViewById(R.id.poview);
        GridView gridView=vp.findViewById(R.id.gagrid);
        Button gasure=vp.findViewById(R.id.gasure);
        Button clean=vp.findViewById(R.id.clean);
        final RelativeLayout poplin=vp.findViewById(R.id.poplin);
        final LinearLayout gachose=vp.findViewById(R.id.gachose);
        pore = vp.findViewById(R.id.pore);
        gasure.setOnClickListener(this);
        clean.setOnClickListener(this);
        gachose.setOnClickListener(this);
        poview.setOnClickListener(this);
        gridView.setAdapter(gPadpter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                for (int j=0;j<galist.size();j++){
                    if (j==i){
                        galist.get(j).setType(1);
                        glItem=galist.get(j);
                    }else {
                        galist.get(j).setType(0);
                    }
                }
                gPadpter.notifyDataSetChanged();
                }
            });

        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        int  mScreenWitdh = outMetrics.widthPixels;
          screenHeight = outMetrics.heightPixels;
        int height = outMetrics.heightPixels;

        popupWindow = new PopupWindow(vp, LinearLayout.LayoutParams.MATCH_PARENT, height);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
        popupWindow.setClippingEnabled(false);
        popupWindow.setAnimationStyle(R.style.popwin_anim_style);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        poplin.addOnLayoutChangeListener(this);
        keyHeight = screenHeight/3;

        popupWindow.showAtLocation(findViewById(R.id.activity_goods), Gravity.NO_GRAVITY, 0, 0);
         }







    public void getPo(){
        isdele=true;
        View vpa = LayoutInflater.from(this).inflate(R.layout.gaa_layout, null, false);
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        int  mScreenWitdh = outMetrics.widthPixels;
        final ImageView gaa=vpa.findViewById(R.id.gaa_back);

        ListView gaa_list=vpa.findViewById(R.id.gaa_list);

        gpladapter = new Gpladapter(this,ciTems);
        gaa_list.setAdapter(gpladapter);

        gaa_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (ciTems.get(i).getChildClass().length()!=0){
                    getPodata(ciTems.get(i).getChildClass());
                }else {
                    fciTem=ciTems.get(i);
                    gdclass.setText(fciTem.getClassName());
                    popus.get(0).dismiss();
                }
            }
         });
        final PopupWindow popupWindowga = new PopupWindow(vpa, mScreenWitdh-200, LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindowga.setFocusable(true);
        popupWindowga.setOutsideTouchable(true);
        popupWindowga.setBackgroundDrawable(new ColorDrawable(Color.GRAY));
        popupWindowga.getContentView().setFocusableInTouchMode(true);
        popupWindowga.getContentView().setFocusable(true);
        popupWindowga.setAnimationStyle(R.style.popwin_anim_style);
        gaa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindowga.dismiss();
            }
        });

        popupWindowga.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (isdele) {
                    if (popus.size()>0) {
                        popus.remove((popus.size() - 1));
                    }
                }
                 }
           });
        popus.add(popupWindowga);
        popupWindowga.showAtLocation(findViewById(R.id.activity_goods), Gravity.NO_GRAVITY, 200, 0);
        }


    public void getPodata(JSONArray ja){
        final ArrayList<CITem> arrciTems=new ArrayList<CITem>();
        for (int i=0;i<ja.length();i++){
            try {
                JSONObject ji=ja.getJSONObject(i);
                String ClassID=ji.getString("ClassID");
                String ClassName=ji.getString("ClassName");
                String FatherId=ji.getString("FatherId");
                String ClassID2=ji.getString("ClassID2");
                JSONArray ChildClass=ji.getJSONArray("ChildClass");
                CITem ciTem=new CITem(ClassID,ClassName,FatherId,ClassID2,ChildClass);
                arrciTems.add(ciTem);
             }catch (JSONException e) {
                e.printStackTrace();
              }
           }
        View vpa = LayoutInflater.from(this).inflate(R.layout.gaa_layout, null, false);
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);

        int  mScreenWitdh = outMetrics.widthPixels;
        ImageView gaa=vpa.findViewById(R.id.gaa_back);
        ListView gaa_list=vpa.findViewById(R.id.gaa_list);

        Gpladapter gpladapter = new Gpladapter(this,arrciTems);
        gaa_list.setAdapter(gpladapter);

        gaa_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
             if (arrciTems.get(i).getChildClass().length()==0){
                 fciTem=arrciTems.get(i);
                 gdclass.setText(fciTem.getClassName());
                 isdele=false;
                 for (int j=0;j<popus.size();j++){
                     popus.get(j).dismiss();
                    }
                 popus.clear();

                }else {
                 getPodata(arrciTems.get(i).getChildClass());
             }
            }
        });
       final PopupWindow popupWindowga = new PopupWindow(vpa, mScreenWitdh-200, LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindowga.setFocusable(true);
        popupWindowga.setOutsideTouchable(true);
        popupWindowga.setBackgroundDrawable(new ColorDrawable(Color.GRAY));
        popupWindowga.getContentView().setFocusableInTouchMode(true);
        popupWindowga.getContentView().setFocusable(true);
        popupWindowga.setAnimationStyle(R.style.popwin_anim_style);

        gaa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindowga.dismiss();
            }
        });
        popupWindowga.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (isdele) {
                    popus.remove((popus.size() - 1));
                }
            }
        });
        popus.add(popupWindowga);
        popupWindowga.showAtLocation(findViewById(R.id.activity_goods), Gravity.NO_GRAVITY, 200, 0);
        }


    @Override
    public void onLayoutChange(View v, int left, int top, int right,
                               int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        if(oldBottom != 0 && bottom != 0 &&(oldBottom - bottom > keyHeight)){

            pore.setVisibility(View.GONE);
        }else if(oldBottom != 0 && bottom != 0 &&(bottom - oldBottom > keyHeight)){
            pore.setVisibility(View.VISIBLE);
           }
          }


    //网络请求
    //获取商品标签
    public  void getLabel(){
        galist.clear();
        OkHttpUtils.get(BaseUrl.goods_label)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean status=js.getBoolean("State");
                            if (status){
                                JSONArray ja=js.getJSONArray("Res");
                               for (int i=0;i<ja.length();i++){
                                 JSONObject ji=ja.getJSONObject(i);
                                   String FlagID=ji.getString("FlagID");
                                   String FlagType=ji.getString("FlagType");
                                   String FlagName=ji.getString("FlagName");
                                   String BGColor=ji.getString("BGColor");
                                   String FontColor=ji.getString("FontColor");
                                   GLItem glItem=new GLItem(0,FlagID ,FlagType,FlagName,BGColor,FontColor);
                                   galist.add(glItem);
                                }
                                gPadpter.notifyDataSetChanged();
                            }else {
                                String msg=js.getString("msg");
                                ToastUtil.showLong(GoodsActivity.this,msg);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                  });
                }


     //获取商品类别请求
     public void getclss(){
         ciTems.clear();
        OkHttpUtils.get(BaseUrl.goods_class)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean state=js.getBoolean("State");
                            if (state){
                              JSONArray ja=js.getJSONArray("Res");
                              for (int i=0;i<ja.length();i++){
                                JSONObject ji=ja.getJSONObject(i);
                                    String ClassID=ji.getString("ClassID");
                                    String ClassName=ji.getString("ClassName");
                                    String FatherId=ji.getString("FatherId");
                                    String ClassID2=ji.getString("ClassID2");
                                    JSONArray ChildClass=ji.getJSONArray("ChildClass");
                                   CITem ciTem=new CITem(ClassID,ClassName,FatherId,ClassID2,ChildClass);
                                   ciTems.add(ciTem);
                                  }
                                gpladapter.notifyDataSetChanged();

                            }else {
                                String msg=js.getString("msg");
                                ToastUtil.showLong(GoodsActivity.this,msg);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                     }
                  });
                 }



             //筛选商品列表
             public void getCGoods(String order, final String page, String flagId, String classId, String min, String max){
                 OkHttpUtils.get(BaseUrl.goods_pager)
                         .params("page",page)
                         .params("size","10")
                         .params("flagId",flagId)
                         .params("classId",classId)
                         .params("keywords",keyword)
                         .params("minPrice",min)
                         .params("maxPrice",max)
                         .params("order",order)
                         .params("sort","true")
                         .execute(new StringCallback() {
                             @Override
                             public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                                 try {
                                     JSONObject js=new JSONObject(s);
                                     boolean State=js.getBoolean("State");
                                     if (State) {
                                         JSONArray ja = js.getJSONArray("Data");
                                         if (page.equals("1")){
                                             gItems.clear();
                                             if (ja.length()==0){
                                                 empty.setVisibility(View.VISIBLE);
                                                 refresh_view.setVisibility(View.INVISIBLE);
                                                 pulist.finishLoading(INIT);
                                                 return;
                                             }else {
                                                 empty.setVisibility(View.INVISIBLE);
                                                 refresh_view.setVisibility(View.VISIBLE);
                                             }
                                         }else {
                                             if (ja.length()==0){
                                                 pulist.finishLoading(STOP);
                                                 return;
                                             }
                                         }


                                         for (int i = 0; i < ja.length(); i++) {
                                             JSONObject ji = ja.getJSONObject(i);
                                             String GoodsId = ji.getString("GoodsID");
                                             String GoodsName = ji.getString("GoodsName");
                                             String GoodsNo = ji.getString("GoodsNO");
                                             String IndexURL = ji.getString("IndexURL");
                                             String Price_Detail = ji.getString("Price_Detail");
                                             String Unit = ji.getString("Unit");
                                             String Sales = ji.getString("Sales");
                                             GItem gItem = new GItem(GoodsId, GoodsName, GoodsNo, IndexURL, Price_Detail, Unit, Sales);
                                             gItems.add(gItem);
                                            }
                                         GdAdapter.notifyDataSetChanged();
                                         pulist.finishLoading(INIT);
                                     }else {

                                         if (page.equals("1")){
                                             pulist.finishLoading(INIT);
                                             if (0==gItems.size()){
                                                 empty.setVisibility(View.VISIBLE);
                                                 refresh_view.setVisibility(View.INVISIBLE);
                                             }
                                         }else {
                                             pulist.finishLoading(STOP);
                                         }

                                     }
                                 } catch (JSONException e) {
                                     e.printStackTrace();
                                 }
                             }
                             @Override
                             public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                                 super.onError(isFromCache, call, response, e);
                             }
                         });
                     }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
      }

   }
